package com.ht.module.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ht.abnormal.HtException;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import com.ht.constant.RedisConstants;
import com.ht.module.sys.dto.LoginDto;
import com.ht.module.sys.dto.RegisterDto;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.service.ISysUserRoleService;
import com.ht.module.sys.service.ISysUserService;
import com.ht.module.sys.service.LoginService;
import com.ht.util.*;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @ProjectName: ht
 * @ClassName: LoginController
 * @Author: hejialun
 * @Description: 登录相关接口
 * @Date: 2021/5/18 23:08
 */
@RestController
@RequestMapping("/sys-login")
@Api(tags = "登录相关接口 ")
public class LoginController {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private LoginService loginService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;


    @ApiOperation("创建验证码")
    @GetMapping(value = "/getCode")
    public JsonResult getCode(String randomStr) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 保存
        redisUtil.set(RedisConstants.VERIFICATION_CODE_PREFIX + randomStr, result, BusConstant.VERIFICATION_CODE_OVERDUE_TIME);
        return JsonResult.success(captcha.toBase64());

    }


    @PostMapping(value = "/login")
    @ApiOperation(value = "登录接口")
    public JsonResult login(@RequestBody @Valid LoginDto en) {
        return JsonResult.success(loginService.login(en));
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public JsonResult logout(HttpServletRequest request) {
        loginService.lougout(request);
        return JsonResult.success();
    }


    @ApiOperation("注册账号")
    @PostMapping("/register")
    public JsonResult register(@RequestBody RegisterDto en, HttpServletRequest request) {
        String code = (String) redisUtil.get(BusConstant.EMAIL_CODE + en.getUsername());
        if (StrUtil.isEmpty(code)) {
            throw new HtException("验证码不存在或已过期！");
        }
        //判断验证码是否正确
        if (!en.getCode().equals(code)) {
            throw new HtException("邮箱验证码不正确！");
        }

        SysUser sysUser = new SysUser()
                .setUsername(en.getUsername())
                .setPassword(en.getPassword())
                .setState(DicConstants.State.ENABLE)
                .setName(en.getUsername());
        //保存用户
        sysUserService.saveObj(sysUser);
        //设置角色
        sysUserRoleService.saveSpecifiedRole(sysUser.getId(), DicConstants.RoleCode.USER);
        //清空redis缓存
        redisUtil.del(BusConstant.EMAIL_CODE + en.getUsername());
        return JsonResult.success("注册成功！");
    }


    //获取邮箱验证码
    @GetMapping("/getEmailCode/{email}")
    public JsonResult getEmailCode(@PathVariable String email) {
        //判断是否有未过期的邮箱验证码
        String notOutDate = (String) redisUtil.get(BusConstant.EMAIL_CODE + email);
        if(BeanUtil.isNotEmpty(notOutDate)){
            throw new HtException("验证码未过期，请勿重复发送！");
        }

        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 6; i++) {       //随机生成一个6位数的验证码
            code.append((int) (Math.random() * 10));
        }
        //发送右键
        new MailUtil(email, code.toString()).run();
        //设置redis缓存-并设置60秒后过去
        redisUtil.set(BusConstant.EMAIL_CODE + email, code, 60);
        return JsonResult.success("发送成功,验证码1分钟后失效！");
    }
}